package com.bbcare.department.plat.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bbcare.comm.*;
import com.bbcare.department.plat.service.impl.DepartmentBasicService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bbcare.department.plat.entity.EducationContent;
import com.bbcare.department.plat.entity.EducationContentInfo;
import com.bbcare.department.plat.entity.EducationTemplate;
import com.bbcare.department.plat.service.IBsStaticParamService;
import com.bbcare.department.plat.service.IEducationManagerService;

import static com.bbcare.comm.Constants.ADD_EDUCATION;

@Controller
@RequestMapping("/service/education")
public class EducationManagerController {

	Logger logger = Logger.getLogger(EducationManagerController.class);

	@Autowired
	private IEducationManagerService educationManagerService;

	@Autowired
	private IBsStaticParamService bsStaticParamService;

	@Autowired
	private DepartmentBasicService departmentBasicService;
	/**
	 * 查询宣教内容详情
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/detail")
	public ResultModel<EducationContentInfo> getEducationDetail(@RequestBody String jsonStr) throws Exception{
		logger.info("in getEducationDetail----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String id = requestParam.getString("contentId");
        if(StringUtils.isEmpty(id)){
        	logger.debug("out getEducationDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教ID不能为空");
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id", id);
        EducationContentInfo info = educationManagerService.getEducationContentById(map);
		logger.info("out getEducationDetail----arg==" + info);
		return new ResultModel<EducationContentInfo>(info);
	}

	/**
	 * 根据科室Id 查询所有宣教
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/list")
	public QueryModel<EducationContentInfo> getEducationlistByCondition(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getEducationlistByCondition----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}


		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

        Map<String,Object> paramMap = requestParam;
        /*paramMap.put("page",jsonEsb.getString("page"));
        paramMap.put("rows",jsonEsb.getString("rows"));
        paramMap.put("sort",jsonEsb.getString("sort"));
        paramMap.put("doctorName",jsonEsb.getString("doctorName"));
        paramMap.put("doctorTitle",jsonEsb.getString("doctorTitle"));
        paramMap.put("deptId",deptId);
        paramMap.put("sortField",jsonEsb.getString("sortField"));*/


        int page =  (paramMap.get("page")!=null && !StringUtils.isEmpty(paramMap.get("page").toString())) ? Integer.parseInt(paramMap.get("page").toString()) : 1;
		int rows =  (paramMap.get("rows")!=null && !StringUtils.isEmpty(paramMap.get("rows").toString())) ? Integer.parseInt(paramMap.get("rows").toString()) : 10;
		paramMap.put("page", rows*(page-1));
		paramMap.put("rows", rows);

        paramMap.put("deptId",deptId);
        List<EducationContentInfo> lists = educationManagerService.getContentlistByCondition(paramMap);

        Map<String,Object> paramTemp = new HashMap<String,Object>();
		paramTemp.put("deptId",deptId);
		paramTemp.put("type",Constants.EDUCATION_PUSH_TYPE_CODE);

        Map<String,String> typeMap =  bsStaticParamService.getStaticParamsForMap(paramTemp);
        EducationContentInfo educationContent = null;
        if(!CollectionUtils.isEmpty(lists)){
        	for(int i = 0;i<lists.size();i++){
        		educationContent = lists.get(i);
        		lists.get(i).setPushTypeName(typeMap.get(educationContent.getTemplateType()));
            }
        }
        Integer count = educationManagerService.getContentsCountByDeptId(paramMap);
		logger.info("out getEducationlistByCondition----arg==" + lists);
		return new QueryModel<EducationContentInfo>(lists,count);
	}


	@ResponseBody
	@RequestMapping("/template/detail")
	public ResultModel<EducationTemplate> getTemplateDetail(@RequestBody String jsonStr) throws Exception{
		logger.info("in getDoctorBasicDetail----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String id = requestParam.getString("templateId");
        if(StringUtils.isEmpty(id)){
        	logger.debug("out getEducationDetail----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教模板ID不能为空");
        }
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("id",id);
        EducationTemplate info = educationManagerService.getTemplateById(map);
		logger.info("out getEducationDetail----arg==" + info);
		return new ResultModel<EducationTemplate>(info);
	}

	/**
	 * 根据科室Id 查询所有宣教模板
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/template/list")
	public QueryModel<EducationTemplate> getTemplatelistByCondition(@RequestBody String jsonStr) throws Exception{
		logger.info("in getEducationlistByCondition----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        Map<String,Object> paramMap = requestParam;

        /*paramMap.put("page",jsonEsb.getString("page"));
        paramMap.put("rows",jsonEsb.getString("rows"));
        paramMap.put("sort",jsonEsb.getString("sort"));
        paramMap.put("doctorName",jsonEsb.getString("doctorName"));
        paramMap.put("doctorTitle",jsonEsb.getString("doctorTitle"));
        paramMap.put("deptId",deptId);
        paramMap.put("sortField",jsonEsb.getString("sortField"));*/

        List<EducationTemplate> lists = educationManagerService.getTemplatelistByCondition(paramMap);
        Integer count = educationManagerService.getTemplateCount(paramMap);
		logger.info("out getEducationlistByCondition----arg==" + lists);
		return new QueryModel<EducationTemplate>(lists,count);
	}


	/**
	 * 根据科室Id 查询所有宣教模板
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/listForDatatableQuery")
	public Map<String, Object> getEducationlistForDateTable(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getEducationlistForDateTable----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

        Map<String,Object> paramMap = requestParam;
        /*paramMap.put("page",jsonEsb.getString("page"));
        paramMap.put("rows",jsonEsb.getString("rows"));
        paramMap.put("sort",jsonEsb.getString("sort"));
        paramMap.put("doctorName",jsonEsb.getString("doctorName"));
        paramMap.put("doctorTitle",jsonEsb.getString("doctorTitle"));
        paramMap.put("deptId",deptId);
        paramMap.put("sortField",jsonEsb.getString("sortField"));*/

        paramMap.put("deptId",deptId);

        // 针对Datatable特殊处理
        String jsonArgs = requestParam.getString(Constants.INF_INPUTPARAM_DATATABLE_FIELD);
        int draw = 0;
        if (!StringUtils.isEmpty(jsonArgs)) {
            JSONObject jsonTable = (JSONObject) JSONObject.parse(jsonArgs);
            draw = jsonTable.getIntValue("draw");
            paramMap.put("page", jsonTable.getIntValue("start"));
            paramMap.put("rows", jsonTable.getIntValue("length"));
        }

        List<EducationContentInfo> lists = educationManagerService.getContentlistByCondition(paramMap);
        Map<String,Object> paramTemp = new HashMap<String,Object>();
		paramTemp.put("deptId",deptId);
		paramTemp.put("type",Constants.EDUCATION_PUSH_TYPE_CODE);

        Map<String,String> typeMap =  bsStaticParamService.getStaticParamsForMap(paramTemp);
        EducationContentInfo educationContent = null;
        if(!CollectionUtils.isEmpty(lists)){
        	for(int i = 0;i<lists.size();i++){
        		educationContent = lists.get(i);
        		lists.get(i).setPushTypeName(typeMap.get(educationContent.getType()));
            }
        }
        // 针对Datatable特殊处理

        Integer count = educationManagerService.getContentsCountByDeptId(paramMap);

        Map<String, Object> retMap = new HashMap<String,Object>();
        retMap.put("draw", draw);
        retMap.put("recordsTotal", count);
        retMap.put("recordsFiltered", count);
        retMap.put("rows", lists);

		logger.info("out getEducationlistForDateTable----arg==" + retMap);
		return retMap;
	}

	/**
	 * 删除宣教内容
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/stopAndEnable")
	public ResultModel<EducationContent> updateEducations(@RequestBody String jsonStr) throws Exception{
		logger.info("in deleteEducations----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String contentId= requestParam.getString("contentId");
        String opCode= requestParam.getString("opCode");
        if(StringUtils.isEmpty(contentId) || StringUtils.isEmpty(opCode)){
        	logger.debug("out deleteEducations----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教ID|opCode不能为空");
        }
        EducationContent ed =  new EducationContent();
        ed.setId(contentId);

        if(opCode.equals(Constants.EDUCATION_STATUS_STOP)){
        	 ed.setStatus(Constants.EDUCATION_STATUS_STOP);
        }else if(opCode.equals(Constants.EDUCATION_STATUS_ENABLE)){
        	ed.setStatus(Constants.EDUCATION_STATUS_ENABLE);
        }else{
        	logger.debug("out deleteEducations----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，操作类型不正确");
        }

        ed.setUpdateTime(DateUtil.getSysDateA());
        educationManagerService.stopEducation(ed);
		logger.info("out deleteDoctors----arg==");
		return new ResultModel<EducationContent>(null);
	}


	/**
	 * 删除宣教内容
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/remove")
	public ResultModel<EducationContent> deleteEducations(@RequestBody String jsonStr) throws Exception{
		logger.info("in deleteEducations----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
        String ids= requestParam.getString("contentIds");

        List<String> list = JSON.parseArray(ids, String.class);
        if(CollectionUtils.isEmpty(list)){
        	logger.debug("out deleteEducations----arg== null");
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教ID不能为空");
        }
        educationManagerService.deleteyContentsByIds(list);
		logger.info("out deleteDoctors----arg==");
		return new ResultModel<EducationContent>(null);
	}

	/**
	 *
	 * @desc 新增修改宣教
	 * @param servletRequest
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("modify")
	public ResultModel<Map<String,String>> modifyEducation(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in EducationModify----arg==" + jsonStr);
		JSONObject jsonEsb = JSON.parseObject(jsonStr);
		JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		if(StringUtils.isBlank(requestParam.getString("bannelUrl"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教logo不能为空");
		}
		if(StringUtils.isBlank(requestParam.getString("content"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教内容不能为空");
		}
		if(StringUtils.isBlank(requestParam.getString("priority"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教权重不能为空");
		}
		if(StringUtils.isBlank(requestParam.getString("type"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，推送规则不能为空");
		}
		if(StringUtils.isBlank(requestParam.getString("templateId"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，模板ID不能为空");
		}
		if(StringUtils.isBlank(requestParam.getString("templateName"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教名称不能为空");
		}
		if(StringUtils.isBlank(requestParam.getString("templateValue"))){
        	throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,"入参校验失败，宣教模板问卷值不能为空");
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
        String authorId = (String) sessionMap.get("authorId");
        String deptId = (String) sessionMap.get("deptId");// 科室id
        String tenantId = (String) sessionMap.get("tenantId");// 租户id

		requestParam.put("createAuthor", authorId);
		requestParam.put("deptId",deptId);//从session获取
		requestParam.put("tenantId",tenantId);//从session获取

        String id = educationManagerService.educationModitfy(requestParam);
		Map<String,String> rspBody = new HashMap<String,String>();
		rspBody.put("id",id);

		// 新增宣教推送id和科室到小程序

		// type=11 宣教新增
		int type = ADD_EDUCATION;
		// system=1 2.0系统
		int system = 1;

		String platType = departmentBasicService.getDepartmentBasicDetails(deptId).getPlatType();

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("type",type);
		jsonObject.put("system",system);
		jsonObject.put("contentId",id);
		jsonObject.put("deptId",deptId);
		jsonObject.put("platType",Integer.parseInt(platType));
		String sendMsg = jsonObject.toJSONString();
		HttpUtil.postData(PropertiesUtils.getProperty("redirectUrl") ,sendMsg);
		logger.info("out EducationModify----arg==" + id);
		return new ResultModel<Map<String,String>>(rspBody);
	}

	/**
	 * 宣教类型列表
	 * @param request
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/educationPushType/list")
	public ResultModel<List<Map<String, Object>>> getEducationPushTypeList(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in getEducationTypeList----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}
		//
		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("deptId");// 科室id
        Map<String,Object> paramTemp = new HashMap<String,Object>();
		paramTemp.put("deptId",deptId);
		paramTemp.put("type",Constants.EDUCATION_PUSH_TYPE_CODE);

		List<Map<String,Object>> list = bsStaticParamService.getStaticParamsByCondition(paramTemp);
		logger.info("out getEducationTypeList----arg==" + list);
		return new ResultModel<List<Map<String,Object>>>(list);
	}

	/**
	 * 宣教浏览按日月统计 当前7天 当前6月
	 * @param request
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping("/browseStatistics")
	public ResultModel<List<Map<String, Object>>> browseStatistics(HttpServletRequest request,@RequestBody String jsonStr) throws Exception{
		logger.info("in browseStatistics----arg==" + jsonStr);
        JSONObject jsonEsb = JSON.parseObject(jsonStr);
        JSONObject requestParam = jsonEsb.getJSONObject(Constants.INF_INPUTPARAM_COMMONFIELD); //统一节点处理
		if(null == requestParam ){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参节点错误，无data节点！");
		}

		// 创建人，从session中获取
        Map<String, Object> sessionMap = ToolUtils.getSessionInfo(request);
//        String tenantId = (String) sessionMap.get("tenantId");// 租户id
        String deptId = (String) sessionMap.get("rootGroupId");// 科室id

        String flag = requestParam.getString("flag");//
        if(StringUtils.isEmpty(flag)){
			throw new AppException(ErrorCode.FOLLOWUP_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR, "入参校验失败，flag不能为空");
        }
        requestParam.put("deptId",deptId);
		List<Map<String,Object>> list = educationManagerService.browseStatistics(requestParam);

		logger.info("out browseStatistics----arg==" + list);
		return new ResultModel<List<Map<String,Object>>>(list);
	}

	@ResponseBody
    @RequestMapping("/uploadEducationLogo")
    public Object uploadQrcode(HttpServletResponse response, HttpServletRequest request) throws Exception {
        logger.info("in uploadEducationLogo==");
        String filepath = "";
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iter = multiRequest.getFileNames();
            if (iter.hasNext()) {
                while (iter.hasNext()) {
                    MultipartFile file = multiRequest.getFile(iter.next());
                    if (!file.isEmpty()) {
                        filepath = OSSClientUtil.uploadPicture(file, PropertiesUtils.getProperty("educationLogo"));// 保存图片
                    }
                }
            } else {
                throw new AppException(ErrorCode.FOLLOW_EXCEPTION_TYPE_UPLOAD_FILE_MPTY, "图片上传失败，上传文件为空");
            }

        }
        logger.info("in uploadEducationLogo==filepath:" + filepath);
        return new ResultModel<Object>(filepath);
    }
}
